package com.candicom.race.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;

class InnerCanvas extends JComponent {

    private final Dimension dim;
    private BufferedImage image;
    private final Color backgroundColor = new Color(255, 255, 255, 0);

    InnerCanvas(Dimension _dim) {
        dim = _dim;
        setPreferredSize(dim);
        setMinimumSize(dim);
        setMaximumSize(dim);
        setSize(dim);

        setOpaque(false);

        image = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gImage = (Graphics2D) image.getGraphics();
        gImage.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gImage.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        gImage.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        gImage.setBackground(backgroundColor);
        gImage.clearRect(0, 0, dim.width, dim.height);
        gImage.dispose();
    }

    void putCars(int x1, int y1, Image car1,int x2, int y2, Image car2) {
        Graphics2D gImage = (Graphics2D) image.getGraphics();
        gImage.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gImage.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        gImage.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        gImage.setBackground(backgroundColor);
        gImage.clearRect(x1-80, y1-80, 160, 160);
        gImage.clearRect(x2-80, y2-80, 160, 160);
        gImage.drawImage(car1, x1 - car1.getWidth(null) / 2, y1 - car1.getHeight(null) / 2, null);
        gImage.drawImage(car2, x2 - car2.getWidth(null) / 2, y2 - car2.getHeight(null) / 2, null);
        gImage.dispose();
        repaint(x1-80, y1-80, 160, 160);
        repaint(x2-80, y2-80, 160, 160);
    }

    @Override
    public void update(Graphics graphics) {
        Graphics2D g = (Graphics2D) graphics.create();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.drawImage(image, null, null);

        g.dispose();
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        update(graphics);
    }
}
